<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2016/11/9
 * Time: 10:50
 */
header("Content-Type: text/html; charset=UTF-8");
require("wx_api/Lib/alipay/AopSdk.php");

/**
 * Class AlipayAction
 * @modify lilei<LL_strive@163.com> 2017-04-27
 */
class AlipayAction extends Action{
    public function submitPay($cid,$sn,$desc,$totalFee){
        Session::switchCustomer(0);
        $alipaySetting = D("customer_mall_alipay_setting");
        $ProductModel = M('module_product_order');
        Session::switchCustomer($cid);
        // 修改从数据库中抓来订单信息(价格)
        // $productPrice = $ProductModel->where('serialNumber = ' . $sn)->getField('price');
        //$totalFee = $productPrice;

        $alipayInfo = $alipaySetting->where("customerId=$cid")->find();
        $c = new AopClient;
        $c->appId = $alipayInfo['appId'];
        //私钥
        $c->rsaPrivateKey=$alipayInfo['rsaPrivateKey'];
        //公钥
        $c->alipayPublicKey = $alipayInfo['alipayrsaPublicKey'];
//        $c->method = 'alipay.trade.wap.pay';
        $req = new AlipayTradeWapPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数
        //此次只是参数展示，未进行字符串转义，实际情况下请转义
        if(strlen($desc)>256){
            $result = preg_split("//u", $desc, -1, PREG_SPLIT_NO_EMPTY);
            $length = 0;
            $desc = '';
            foreach($result as $key=>$value){
                $length+=strlen($value);
                if($length<=253){
                $desc.=$value;
                }
            }
            $desc.="...";
        }
        $totalFee= number_format($totalFee, 2, '.', '');
        $req->setNotifyUrl(C('SERVER_HOST')."AlipayBack/callback.json");
        $req->setReturnUrl(C('SERVER_HOST')."Alipay/callBack.json");
        $req->setBizContent("{" .
            "    \"subject\":\"$desc\"," .
            "    \"out_trade_no\":\"$sn\"," .
            "    \"total_amount\":$totalFee" .
            "  }");
        $response= $c->pageExecute ($req);
        echo $response;
    }
    public function orderRefund($cid,$trade_no,$refundId,$refundMoney, $oid){
        Session::switchCustomer(0);
        $alipaySetting = D("customer_mall_alipay_setting");
        Session::switchCustomer($cid);
        $alipayInfo = $alipaySetting->where("customerId=$cid")->find();
        $c = new AopClient;
        $c->appId = $alipayInfo['appId'];
        //私钥
        $c->rsaPrivateKey=$alipayInfo['rsaPrivateKey'];
        //公钥
        $c->alipayrsaPublicKey = $alipayInfo['alipayPublicKey'];
        $req = new AlipayTradeRefundRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数
        //此次只是参数展示，未进行字符串转义，实际情况下请转义
        $refund= number_format($refundMoney/100, 2, '.', '');
        $req->setBizContent("{" .
            "    \"trade_no\":\"$trade_no\"," .
            "    \"refund_amount\":$refund," .
            "    \"out_request_no\":\"$refundId\"" .
            "  }");
        $result = $c->execute ( $req);
        $responseNode = str_replace(".", "_", $req->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            R('Product/refundStatistics', array($oid,$refundMoney));
            ProductOrder::updateOrderRefund($oid, $refundId, true, "");
        } else {
            Log::write("退款失败  ".$result->$responseNode->sub_msg);
        }
        return;
    }
    public function callBack(){
        $sn =  $_GET['out_trade_no'];
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        $orderInfo = $orderModel->where("tempSerialNumber = '$sn'")->find();
        $oid = $orderInfo['id'];
        $cid = $orderInfo['fromCustomerId'];
        if($orderInfo['fromUserName']){
            $userName = $orderInfo['fromUserName'];
            cookie("openid_$cid",$userName);
            Session::$user['userName']=$userName;
        }
        Session::switchCustomer($cid);
        $pa = new stdClass();
		$url = WeixinApi::getDomainName();
        if($orderInfo['freebuy']){
            $pa->oid=$oid;
            $url = $url['SERVER_HOST']."call.html?customerId=$cid&module=freebuy&method=getView&params={\"oid\":\"$oid\"}";
        }else if($orderInfo['isTeam']){
            $pa->teamId=$orderInfo['teamId'];
            $pa->id=$oid;
            $url = $url['SERVER_HOST']."call.html?customerId=$cid&module=tuan&method=getView&params={\"teamId\":\"".$orderInfo['teamId']."\",\"id\":\"$oid\"}";
        }else if($orderInfo['isVirtual']){
            $pa->id=$oid;
            $pa->tplid=1;
            $url = $url['SERVER_HOST']."call.html?customerId=$cid&module=product&method=virtualSuccess&params={\"id\":\"$oid\"}";
        }else if($orderInfo['orderType']==3){
            $pa->parId=$orderInfo['playOrderId'];
            $pa->id=$oid;
            $url = $url['SERVER_HOST']."call.html?customerId=$cid&module=allChips&method=indianaSuccess&params={\"id\":\"$oid\",\"parId\":\"".$orderInfo['playOrderId']."\"}";
        }else{
            $pa->id=$oid;
            $pa->tplid=1;
            $url = $url['SERVER_HOST']."call.html?customerId=$cid&module=product&method=orderSuccess&params={\"tplid\":1,\"id\":\"$oid\"}";
        }
        $userInfo['userName']=$orderInfo['fromUserName'];
        $send = Module::callModule("product",$userInfo,"sendNotice",$pa);
        if($send['sendId']){
            $url = $url['SERVER_HOST']."call.html?customerId=$cid&module=product&method=orderSuccess&params={\"tplid\":1,\"id\":\"$oid\",\"sendId\":\"".$send['sendId']."\"}";
        }
        redirect($url);
    }
}